
#include "DatabaseConnManage.h"
#include "DatabaseConn.h"
#include <iostream>

LIBDBC_BEGIN_NAMESPACE

DatabaseConnManage::DatabaseConnManage(void)
{
}

DatabaseConnManage::~DatabaseConnManage(void)
{
  int n = static_cast<int>(_connections.size())-1;

  while ( n>=0 )
  {
    DatabaseConn* pDC = _connections.getByIndex(n);
    if ( pDC )
    {
      delete pDC;
    }
    n--;
  }
  _connections.clear();
}

bool DatabaseConnManage::setConnection(string key, string dbms, string host, string database, string user, string pwd)
{
  bool bAdded = true;
  
  if ( _connections.has( key ))
  {
    delete _connections.get(key);
  }
  
  DatabaseConn* con;
  if ( user.length() > 0 )
  {
    // login with user/pwd
    con = new DatabaseConn( dbms, host, database, user, pwd );
  }
  else
  {
    // login using automatic mechanisms (could differ on implementation)
    // example: SqlServer2005 uses window authentication if no user/pwd is given
    //          MySQL uses default user and no password
    //          SqLite has no user/pwd mechanisms - no need to give some
    //          and so on
    con = new DatabaseConn( dbms, host, database );
  }

  bAdded = this->_connections.set( key, con );

  return bAdded;
}

IDatabase* DatabaseConnManage::getOpenConnectionHandle(string key)
{
  DatabaseConn* con;
  con = _connections.get( key );
  if ( !con ) 
    return NULL; 

  return con->getConnectedDatabaseHandler();
}

void DatabaseConnManage::markConnectionHandleUnused(string key)
{
  DatabaseConn* con;
  if ( (con = _connections.get( key )) )
  {
    con->markConnectionUnused();
  }
}

bool DatabaseConnManage::hasConnection(string key)
{
  return _connections.has( key );
}


bool DatabaseConnManage::removeConnection(string key)
{
  bool bDeleted = false;
  DatabaseConn* con = _connections.get( key );
  if ( con )
  {
    delete con;
    _connections.remove( key );
    bDeleted = true;
  }
  return bDeleted;
}

LIBDBC_END_NAMESPACE

